<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Book_Booklet extends Controller{

public function action_index()
{
}

public function action_list()
{
	$booklet = ORM::factory('booklet');
	if ($_GET)
	{
		$category_id = arr::get($_GET, 'category_id');
		$page = arr::get($_GET, 'page');
		$num_in_page = arr::get($_GET, 'num_in_page');
		$order = arr::get($_GET, 'order');
		$lock = arr::get($_GET, 'lock');
		if ($category_id)
		{
			$category = ORM::factory('category')->where('id', '=', $category_id)->find();
			if ($category->loaded())
			{
				$booklet = $category->booklets;
			}
		}
		if ($order != NULL)
		{
			switch ($order)
			{
			case 0:
				$booklet->order_by('create_time', 'DESC');
				break;
			case 1:
				$booklet->order_by('create_time', 'ASC');
				break;
			case 2:
				$booklet->order_by('download_count', 'DESC');
				break;
			default:
				break;
			}
		}
		if ($lock != NULL)
		{
			switch ($lock)
			{
			case 0:
				$booklet->where('lock', '=', 'off');
				break;
			case 1:
				$booklet->where('lock', '=', 'on');
				break;
			default:
				break;
			}
		}
	}
	$query_result = $booklet->find_all();
	if (isset($page) AND isset($num_in_page))
	{
		$result = Book_Booklet::instance()->create_booklet_list(array_slice($query_result->as_array(), ($page - 1) * $num_in_page, $num_in_page));
	}
	else
	{
		$result = Book_Booklet::instance()->create_booklet_list($query_result->as_array());
	}
	json_Output::write($result);
}

public function action_image()
{
	$booklet_id = arr::get($_GET, 'booklet_id');
	if ($booklet_id)
    {
		$booklet = ORM::factory('booklet')->where('id', '=', $booklet_id)->find();
		if ($booklet->loaded())
		{
			Book_Picture::instance()->render_thumb($booklet->get_image());
		}
		else
		{
			header("Status: 400 书id不存在");
		}
	}
	else
	{
		header("Status: 400 参数为空");
		return;
	}
}

public function action_thumbnail()
{
	$booklet_id = arr::get($_GET, 'booklet_id');
	if ($booklet_id)
    {
		$booklet = ORM::factory('booklet')->where('id', '=', $booklet_id)->find();
		if ($booklet->loaded())
		{
			Book_Category::instance()->render_thumb($booklet->image);
		}
		else
		{
			header("Status: 400 书id不存在");
			return;
		}
	}
	else
	{
		header("Status: 400 参数为空");
		return;
	}
}

}



